from typing import List, Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps
from app.schemas.common import Response

router = APIRouter()

@router.get("/", response_model=Response[List[schemas.QuestionSet]])
def read_question_sets(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
) -> Any:
    """
    获取题集列表
    """
    try:
        question_sets = crud.question_set.get_multi(db, skip=skip, limit=limit)
        return Response(code=200, data=question_sets, msg="获取题集列表成功")
    except Exception as e:
        return Response(code=500, data=None, msg=str(e))

@router.post("/", response_model=Response[schemas.QuestionSet])
def create_question_set(
    *,
    db: Session = Depends(deps.get_db),
    question_set_in: schemas.QuestionSetCreate,
) -> Any:
    """
    创建新题集
    """
    try:
        question_set = crud.question_set.create(db=db, obj_in=question_set_in)
        return Response(code=200, data=question_set, msg="创建题集成功")
    except Exception as e:
        return Response(code=500, data=None, msg=str(e))

@router.get("/{id}", response_model=Response[schemas.QuestionSetWithQuestions])
def read_question_set(
    *,
    db: Session = Depends(deps.get_db),
    id: int,
) -> Any:
    """
    通过ID获取题集详情
    """
    try:
        question_set = crud.question_set.get_with_questions(db=db, id=id)
        if not question_set:
            return Response(code=404, data=None, msg="题集不存在")
        return Response(code=200, data=question_set, msg="获取题集详情成功")
    except Exception as e:
        return Response(code=500, data=None, msg=str(e))

@router.put("/{id}", response_model=Response[schemas.QuestionSet])
def update_question_set(
    *,
    db: Session = Depends(deps.get_db),
    id: int,
    question_set_in: schemas.QuestionSetUpdate,
) -> Any:
    """
    更新题集
    """
    try:
        question_set = crud.question_set.get(db=db, id=id)
        if not question_set:
            return Response(code=404, data=None, msg="题集不存在")
        question_set = crud.question_set.update(db=db, db_obj=question_set, obj_in=question_set_in)
        return Response(code=200, data=question_set, msg="更新题集成功")
    except Exception as e:
        return Response(code=500, data=None, msg=str(e))

@router.delete("/{id}", response_model=Response[schemas.QuestionSet])
def delete_question_set(
    *,
    db: Session = Depends(deps.get_db),
    id: int,
) -> Any:
    """
    删除题集
    """
    try:
        question_set = crud.question_set.get(db=db, id=id)
        if not question_set:
            return Response(code=404, data=None, msg="题集不存在")
        question_set = crud.question_set.remove(db=db, id=id)
        return Response(code=200, data=question_set, msg="删除题集成功")
    except Exception as e:
        return Response(code=500, data=None, msg=str(e)) 